layui.use(['layer', 'form', 'table', 'admin', 'ax', 'func', 'laydate', 'upload', 'element', 'tree', 'ztree', 'util'], function () {
    var $ = layui.$;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    var laydate = layui.laydate;
    var upload = layui.upload;
    var element = layui.element;
    var tree = layui.tree;
    var ztree = layui.ztree;
    var util = layui.util


    laydate.render({
        elem: '#timeLimit',
        range: true,
        trigger: 'click',
        //max: Feng.currentDate()
    });
    var Notice = {
        tableId: "noticeTable", //表格id
    };

    //初始化日期
    function format(fmt, date) {
        var o = {
            "M+": date.getMonth() + 1, //月份
            "d+": date.getDate(), //日
            "h+": date.getHours(), //小时
            "m+": date.getMinutes(), //分
            "s+": date.getSeconds(), //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }

    var dateFirst = new Date();
    dateFirst.setDate(1);
    var firstDay = format('yyyy-MM-dd', dateFirst);
    var times = new Date();
    var today = format('yyyy-MM-dd', times);
    var dateStr = firstDay + "-" + today;
    $('#timeLimit').val(dateStr);

    // 刷新表格
    Notice.onClickShop = function (obj) {
        let shopTreeId = obj.data.id;
        var languageAjax = new $ax(Feng.ctxPath + "/btyShopTree/getOneById?shopId=" + shopTreeId);
        var languageResult = languageAjax.start();
        //只有点击的是门店数据才会触发查询
        if (languageResult != null && languageResult != "" && languageResult != undefined) {
            //门店名重新赋值
            $('#dm').val(languageResult.shopCode);
            form.render('select');
            Notice.search(languageResult.shopCode);
        }
    };
// 初始化树
    tree.render({
        elem: '#shop',
        data: getData(),
        onlyIconControl: true,
        showLine: false,
        click: Notice.onClickShop,
    });


    /**
     * 检索店名
     */
    var languageAjax = new $ax(Feng.ctxPath + "/btyShop/selectAll");
    var languageResult = languageAjax.start();
    console.info(languageResult);
    $.each(languageResult, function (index, val) {
        $("#dm").append("<option value='" + val.shopCode + "'>" + val.shopName + "</option>");
    });
    form.render('select');

    /**
     * 初始化表格的列
     */
    Notice.initColumn = function () {
        return [[
            {type: 'checkbox', LAY_CHECKED: true, hide: true},
            {field: 'shopName', align: "center", sort: true, title: '店名', width: 190},
            {field: 'pl', align: "center", sort: true, title: '品类', width: 180},
            {field: 'xm', align: "center", sort: true, title: '项名'},
            {field: 'result', align: "center", sort: true, title: '库存'},
            {field: 'unit', align: "center", sort: true, title: '单位'},
            {field: 'sl', title: '数量', align: 'center', width: 60, edit: 'text'},
            {field: 'printAmount', title: '金额', align: 'center', sort: true, width: 120, edit: 'text'},
            {field: 'date', align: "center", hide: true, title: '查询日期'}
        ]];
    };
    table.on('edit(noticeTable)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

        var data = obj.data; //获得当前行数据
        var field = obj.field;

        var thisobj = $(this);

        var slVal = obj.data.sl;
        var date = obj.data.date;

        if (obj.data.sl != null && obj.data.sl != '' && obj.data.sl != undefined &&
            obj.data.printAmount != null && obj.data.printAmount != '' && obj.data.printAmount != undefined) {
            $.ajax({
                url: "btyInventory/selectMoney",
                type: "POST",
                dataType: "json",
                data: data,
                async: false,
                success: function (obj) {
                    if (obj == true) {
                        thisobj.parents("tr").css({color: "red"});
                    }
                }
            })
        }


    });


    /**
     * 点击查询按钮
     */
    Notice.search = function (shopCode) {
        var queryData = {};
        let dm = $("#dm").val();
        if (shopCode != null) {
            dm = shopCode;
        }
        queryData['dm'] = shopCode;
        queryData['pl'] = $("#pl").val();
        queryData['timeLimit'] = $("#timeLimit").val();
        table.reload(Notice.tableId, {
            where: queryData, page: {curr: 1}
        });

    };
    //渲染表格
    var tableResult = table.render({
        elem: '#' + Notice.tableId,
        url: Feng.ctxPath + '/dsstoreBill/getStoreData',
        page: true,
        height: "full-155",
        cellMinWidth: 100,
        limit: 20,
        totalRow: true,	//开启合计行
        cols: Notice.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        Notice.search();
    });
});

// 获取tree数据
function getData() {
    var data = [];
    $.ajax({
        url: "/btyShopTree/layuiTree",
        type: "post",
        async: false,
        success: function (result) {
            data = result;
        }
    });
    return data;
}

// tree收缩按钮
$(function () {
    var panehHidden = false;
    if ($(this).width() < 769) {
        panehHidden = true;
    }
    $('#myContiner').layout({initClosed: panehHidden, west__size: 260});
});